import { useEffect, useState } from "react";

/**
 * 考试模式检测Hook
 * 用于检测当前是否处于考试状态，自动禁用数字人助手等功能
 */
export const useExamMode = () => {
  const [isExamMode, setIsExamMode] = useState(false);

  useEffect(() => {
    const checkExamMode = () => {
      const currentPath = window.location.pathname;

      // 检测考试相关路径
      const examPaths = [
        "/exam-taking",
        "/exam",
        "/test",
        "/quiz",
        "/examination",
      ];

      const isInExam = examPaths.some((path) => currentPath.includes(path));

      // 检测URL参数中是否包含考试标识
      const urlParams = new URLSearchParams(window.location.search);
      const isExamParam = urlParams.get("mode") === "exam";

      setIsExamMode(isInExam || isExamParam);
    };

    // 初始检测
    checkExamMode();

    // 监听路由变化
    const handlePopState = () => {
      checkExamMode();
    };

    window.addEventListener("popstate", handlePopState);

    // 监听页面可见性变化（防止切换标签页）
    const handleVisibilityChange = () => {
      if (isExamMode && document.hidden) {
        console.warn("考试期间不允许切换页面！");
        // 可以在这里添加警告或记录日志
      }
    };

    document.addEventListener("visibilitychange", handleVisibilityChange);

    return () => {
      window.removeEventListener("popstate", handlePopState);
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  }, [isExamMode]);

  return {
    isExamMode,
    // 提供手动设置考试模式的方法
    setExamMode: setIsExamMode,
  };
};
